package com.ljx.itbbs.server.article.event.handler;

import cn.hutool.core.collection.CollUtil;
import com.ljx.itbbs.server.article.event.ArticleUpdateEvent;
import com.ljx.itbbs.server.article.service.ArticleTagService;
import com.ljx.itbbs.server.article.service.ResourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;

import java.util.Objects;

/**
 * @Author: LiJunXi
 * @Description:
 * @Date: 2024-03-31  22:50
 */
@Component
public class ArticleUpdateEventHandler {

    @Autowired
    private ArticleTagService articleTagService;

    @Autowired
    private ResourceService resourceService;

    /**
     * 更新文章标签
     * @param event
     */
    @Async
    @TransactionalEventListener(phase = TransactionPhase.BEFORE_COMMIT, classes = ArticleUpdateEvent.class, fallbackExecution = true)
    public void updateArticleTag(ArticleUpdateEvent event) {
        articleTagService.updateArticleTag(event.getArticleId(), event.getTagList());
    }

    /**
     * 若是存在附件就保存附件
     * @param event
     */
    @Async
    @TransactionalEventListener(phase = TransactionPhase.BEFORE_COMMIT, classes = ArticleUpdateEvent.class, fallbackExecution = true)
    public void updateArticleResource(ArticleUpdateEvent event) {
        // 将之前存在的与文章相关的资源全部清除
        resourceService.clearArticleId(event.getArticleId());
        if (CollUtil.isNotEmpty(event.getResourcesList()) && Objects.nonNull(event.getIntegral()) && Objects.nonNull(event.getIsFree())){
            // 更新资源信息
            resourceService.batchUpdateResource(event.getResourcesList(), event.getIsFree(), event.getIntegral(), event.getArticleId());
        }
    }
}
